package com.wuze.cloud.aop;

import com.wuze.cloud.context.RedisContext;
import com.wuze.cloud.exception.SysGlobalException;
import com.wuze.cloud.pojo.SysStorageDO;
import com.wuze.cloud.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.wuze.cloud.enums.SysGlobalExceptionEnum.SPACE_NOT_ENOUGH;

/**
 * @Author wuze
 * @Date 2023/5/19 9:52
 * @ClassName: SysAop
 * @Description: TODO
 */
@Aspect
@Component
@Slf4j
public class SysFileAop {

    @Autowired
    private RedisUtil redisUtil;

    //切入点:待增强的方法
    @Pointcut("execution(public * com.wuze.cloud.dao.SysStorageDao.update(..))" )
    //切入点签名
    public void log(){
        System.out.println("pointCut签名。。。");
    }
    //前置通知
    @Before("log()")
    public void deBefore(JoinPoint jp) throws Throwable {

        Object[] args = jp.getArgs();
        SysStorageDO storage = (SysStorageDO)args[0];
        if(storage.getCurrSize()>storage.getMaxSize()){
            throw new SysGlobalException(SPACE_NOT_ENOUGH.getCode(),SPACE_NOT_ENOUGH.getMsg());
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date today = new Date();
        //清理缓存
        redisUtil.del(RedisContext.KEY+":5");
        redisUtil.del(RedisContext.KEY+":10");
        redisUtil.del(RedisContext.KEY+":20");
        redisUtil.del(RedisContext.USER_KEY+storage.getUserId());

        redisUtil.del(RedisContext.USER_UPLOAD_DATA + format.format(today)+"_"+storage.getUserId());
        redisUtil.del(RedisContext.ADMIN_UPLOAD_DATA+format.format(today));

    }
    //返回通知
    @AfterReturning(returning = "ret", pointcut = "log()")
    public void doAfterReturning(JoinPoint jp,Object ret) throws Throwable {

    }

    //异常通知
    @AfterThrowing(throwing = "ex", pointcut = "log()")
    public void throwss(JoinPoint jp, Exception ex) {
        log.error("修改空间出错:{}", ex.getMessage());
    }

    //后置通知
    @After("log()")
    public void after(JoinPoint jp) throws InterruptedException {
        //延时双删
        Thread.sleep(1000);
        Object[] args = jp.getArgs();
        SysStorageDO storage = (SysStorageDO)args[0];
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date today = new Date();
        redisUtil.del(RedisContext.KEY+":5");
        redisUtil.del(RedisContext.KEY+":10");
        redisUtil.del(RedisContext.KEY+":20");
        redisUtil.del(RedisContext.USER_KEY+storage.getUserId());

        redisUtil.del(RedisContext.USER_UPLOAD_DATA + format.format(today)+"_"+storage.getUserId());
        redisUtil.del(RedisContext.ADMIN_UPLOAD_DATA+format.format(today));
    }
}
